package de.luisoft.ui.control;

import java.util.List;
import java.util.logging.Logger;

import com.vaadin.data.Validator.EmptyValueException;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Form;
import com.vaadin.ui.Window;

import de.luisoft.dao.MyDAO;
import de.luisoft.dto.WahlDTO;
import de.luisoft.ui.view.TwinPanel;
import de.luisoft.util.SendMail;

public class SendClickListener implements ClickListener {

	private static final long serialVersionUID = -6865367629141437719L;

	private static final Logger log = Logger.getLogger(SendClickListener.class
			.getName());

	private Form f;
	private WahlDTO w;
	private TwinPanel t;

	public SendClickListener(Form f, WahlDTO w, TwinPanel t) {
		this.f = f;
		this.w = w;
		this.t = t;
	}

	public void buttonClick(ClickEvent event) {

		log.info("Button clicked" + w + ";" + event.getButton().isValid());
		f.setComponentError(null);
		try {
			f.commit();
			// f.setVisible(false);
			log.info("Button clicked" + w);

			List<String> c = t.getAllSelected();
			w.setSelect(c);

			MyDAO dao = new MyDAO();
			long key = dao.saveEntry(w);

			SendMail sm = new SendMail();
			sm.send(w, key);

			Window.Notification n = new Window.Notification("Deine Wahl",
					Window.Notification.TYPE_TRAY_NOTIFICATION);
			n.setPosition(Window.Notification.POSITION_CENTERED);
			StringBuffer strb = new StringBuffer();
			int i = 1;
			if (w.getSelect() != null) {
				for (String p : w.getSelect()) {
					strb.append(i + ". " + p + "<br/>");
					i++;
				}
			}
			n.setDescription("Hallo " + w.getVorname() + " " + w.getName()
					+ ",<br/><br/>"
					+ " du hast die folgenden Projekte ausgewählt<br/><br/>"
					+ strb + "<br/>Sende Mail an " + w.getEmail());
			f.getWindow().showNotification(n);

		} catch (EmptyValueException e) {
			// ignore e.printStackTrace();
		} catch (InvalidValueException e) {
			System.out.println("e=" + e);
			//f.discard();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
